<?php
namespace app\crm\model;

use app\mini\model\AdminUser;
use think\facade\Db;
use app\admin\model\Common;
use app\admin\model\ShopModel;

class ReturnConsult extends Common
{
    protected $name = 'return_consult';


    //咨询列表
    public function getDataList(array $request): array
    {


        $where = [];
        // 客户ID
        if(!empty($request['customer_id']))
        {
            $where[] = ['r.customer_id','=',$request['customer_id']];
        }
        if(!empty($request['customer_name']))
        {
            $where[] = ['c.customer_name','like','%'.$request['customer_name'].'%'];
        }
        if(!empty($request['consult_id']))
        {
            $where[] = ['r.consult_id','=',$request['consult_id']];
        }
        if(!empty($request['work_name'])){
            $adminuser_ids = AdminUser::where('realname','like','%'.$request['work_name'].'%')->column('id');
            $where[] = ['r.consult_id','in',$adminuser_ids];
        }
        //咨询时间
        if(!empty($request['start']) || !empty($request['end']))
        {

            if(!empty($request['start']))
            {
                $start = strtotime($request['start'].'00:00:00');

            }else
            {
                $start = strtotime(time().'00:00:00');
            }
            if(!empty($request['end']))
            {
                $over = strtotime($request['end'].'23:59:59');
            }else
            {
                $over = strtotime(time().'23:59:59');
            }
            $where[] = ['r.consult_time','between',[$start, $over]];
        }

        if($request['export'] != 1)
        {
            $page = $request['page'] ?? 1;
            $pagesize = $request['pagesize'] ?? 10;
            // 查询数据
            $res = [];
            $res =  $this->field('r.*, a.realname as consult_name, c.customer_name, c.telephone, s.shop_name')
            ->order('r.id','DESC')
            ->alias('r')
            ->leftJoin('customer c','r.customer_id = c.id')   // 顾客
            ->leftJoin('shop s','s.shop_id = c.shop_id')   // 店铺
            ->leftJoin('admin_user a','r.consult_id = a.id') // 添加人
            ->where($where)
            ->paginate([
                'list_rows'=>$pagesize,
                'page'=>$page,
                'query'=>request()->param()
            ]);
            if(!empty($res))
            {
                $res = json_decode(json_encode($res),true);
            }
        }else
        {
            // 查询数据
            $res = [];
            $res =  $this->field('r.*, a.realname as consult_name, c.customer_name, c.telephone, s.shop_name')
            ->order('r.id','DESC')
            ->alias('r')
            ->leftJoin('admin_user a','r.consult_id = a.id') // 添加人
            ->leftJoin('customer c','r.customer_id = c.id')   // 顾客
            ->leftJoin('shop s','s.shop_id = c.shop_id')   // 店铺
            ->where($where)
            ->select()
            ->toArray();
        }
        // var_dump($res);die;
        return $res;
    }




    //添加
    public function addData(array $request)
    {
        Db::startTrans();
        try
        {
            // 定义必填字段及其中文名称
            $requiredFields = [
                'customer_id' => '顾客ID',
                'consult_id' => '填写人ID',

                'consult_content' => '咨询内容',
                'consult_time' => '咨询时间',
            ];
            foreach ($requiredFields as $field => $name)
            {
                if (!array_key_exists($field, $request))
                {
                    $this->error = "{$name}不能为空";
                    return false;
                }
            }

            // 将咨询时间转换为时间戳
            if (isset($request['consult_time']))
            {
                // 如果已经是时间戳格式（整数），直接使用
                if (is_numeric($request['consult_time']) && $request['consult_time'] > 0)
                {
                    $consultTime = (int)$request['consult_time'];
                }else
                {
                // 如果是日期字符串，尝试转换为时间戳
                    $consultTime = strtotime($request['consult_time']);
                    if ($consultTime === false)
                    {
                        $this->error = "咨询时间格式无效，请提供有效的时间格式";
                        return false;
                    }
                }

                // 更新请求数据中的咨询时间
                $request['consult_time'] = $consultTime;
            }

            unset($request['user_id']);
            if(!empty($request['id']))
            {
                $id = $request['id'];
                $request['update_time'] = time();
                $this->where('id',$id)->update($request);
            }else
            {
                $request['create_time'] = time();
                $id = $this->insertGetId($request);
            }
            Db::commit();
            return ['id'=>$id];
        }catch (\Exception $e)
        {
            Db::rollback(); // 回滚
            $this->error = '添加失败';
            return [];
        }
    }

}
